﻿var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');//用户请求日志中间件,主要功能是：在控制台中，显示req请求的信息
var cookieParser = require('cookie-parser');//解析Cookie头和填充req.cookies 中间件
var bodyParser = require('body-parser');//请求内容解析中间件
var expressSession = require('express-session');//简单的基于会话中间件。
var mongoose = require('mongoose');
var mongoStore = require('connect-mongo')(expressSession);//将connect的session持久化到mongodb中的
var dbUrl = 'mongodb://cyj:123456@127.0.0.1:27017/yongjin';//默认开发连接
var config = require('./config/conf.json');

if (process.env.VCAP_SERVICES) {//实际环境中
    var db_config = JSON.parse(process.env.VCAP_SERVICES).mongodb[0].credentials;
    dbUrl = db_config.uri;
}
// 调用 express 实例，它是一个函数，不带参数调用时，会返回一个 express 实例，将这个变量赋予 app 变量。
var app = express();

//#region 配置view 目录，以及模板引擎
app.set('views', path.join(__dirname, 'views'));
var laytpl = require('laytpl');
laytpl.config = { cache: true };
app.engine('.html', laytpl.__express);
app.set('view engine', 'html');
//#endregion
//如果不愿意使用默认的layout.ejs，则可以设置layout为false
//app.set('view options', {
//    "layout": false,
//});
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));//将每个请求记录到控制台
// 定义数据解析器
app.use(bodyParser.json());// parse application/json  
app.use(bodyParser.urlencoded({ extended: false }));// parse application/x-www-form-urlencoded  
app.use(cookieParser());
//app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'www')));

app.use(expressSession({
    secret: 'yongjin',
    store: new mongoStore({
        url: dbUrl,
        collection: 'sessions'
    }),
    cookie: { maxAge: 30 * 60 * 1000 }, //设置maxAge是600000ms，即10分钟后session和相应的cookie失效过期
    resave: true,
    saveUninitialized: true
}));

//添加路由
require('./config/routes')(app);
//运行： NODE_ENV=dev node app.js
if ('dev' === app.get('env')) {
    mongoose.set('debug', true);
}
var MongoDB = mongoose.connect(dbUrl).connection;
MongoDB.on('error', function (err) { console.log("mongodb error::" + err.message); });
MongoDB.once('open', function () {
    console.log("mongodb connection open");
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
/*
 * bin, 存放启动项目的脚本文件
 * node_modules, 存放所有的项目依赖库。
 * public，静态文件(css,js,img)
 * routes，路由文件(MVC中的C,controller)
 * views，页面文件(模板)
 * package.json，项目依赖配置及开发者信息
 * app.js，应用核心配置文件



 "dependencies": {
"express": "~4.9.0",
"express-session": "^1.11.3",
"body-parser": "~1.8.1",
"cookie-parser": "~1.3.3",
"morgan": "~1.3.0",//打印的nodejs 服务器接受到的请求的信息。
"serve-favicon": "~2.1.3",
"debug": "~2.0.0",//打印的是开发者自己在 控制台 打印的信息，它的目的是要代替 console.log() 
"laytpl": "^1.2.0",
"less": "^2.5.0",
"connect-mongo": "^0.8.1",
"mongoose": "^4.1.2",//http://ourjs.com/detail/53ad24edb984bb4659000013
"method-override": "^2.3.3",//http://m.blog.csdn.net/blog/boyzhoulin/40146197
"superagent": "^1.2.0",//https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
"underscore": "^1.8.3",
"marked": "^0.3.3",//Markdown解析器
"moment": "^2.10.3",//http://momentjs.cn/  日期
"utility": "^1.3.1",//https://www.npmjs.com/package/utility md5,has,base64,html escape 等
"bcrypt-nodejs": "*",//https://www.npmjs.com/package/bcryptjs 加密 https://github.com/shaneGirish/bcrypt-nodejs/
"cheerio": "^0.19.0",//为服务器特别定制的，快速、灵活、实施的jQuery核心实现.
 "xml2js":"^0.4.15"//https://www.npmjs.com/package/xml2js 解析xml
}
 *  */